<?php

declare (strict_types = 1);

namespace app\certificate\controller\admin\v1;


use think\facade\Db;
use think\Request;
use libs\Dictionary;
use libs\Image;
use libs\ALiOss;

class Train{
   /**
    * @Description: 
    * @Author: Terry
    * @Date: 2024-01-31 16:41:47
    * @param {Request} $request
    */    
    public function getList(Request $request){
        $data  = $request->data;
        $limit =  $data['limit'];
        $page =  $data['page'];
        $where = [
            ['projectCode','=',$request->authWhere['projectCode']],
            ['isDelete','=','0'],
        ];

        if(!empty($data['name'])) array_push($where,['name','like',"%".$data['name']."%"]);
        // if(!empty($data['templateUuid'])) array_push($where,['templateUuid','=',$data['templateUuid']]);

        //判断身份
        if(isset($request->authWhere['corpCode'])){
            array_push($where,['corpCode','=',$request->authWhere['corpCode']]);
        }elseif(!empty($data['corpCode'])){
            array_push($where,['corpCode','=',$data['corpCode']]);
        }


        switch($data['expiryDate']){
            case 'entry':
                array_push($where,['expiredTime','>',date('Y-m-d H:i:s')]);
            break;
            case 'expired':
                array_push($where,['expiredTime','<=',date('Y-m-d H:i:s')]);
            break;
        }

        $list =  DB::table('certificate_train')
        ->where($where)
        ->page((int)$page,(int)$limit)
        ->field(['inDate','corpCode','name','remark','uuid','qrCode','expiredTime','lecturer'])
        ->order(['id desc'])
        ->select()->toArray();

        foreach ($list as $key => &$value) {
            $value['checkInCount'] = DB::table(['certificate_trainCheckIn'])->where(['trainUuid'=>$value['uuid'],'isDelete'=>0])->count();
        }

        $count =  DB::table('certificate_train')
        ->where($where)
        ->count('id'); 

        $data = [
            'list'=>$list,
            'count'=>$count,
        ];
        return result(SUCCESS,$data,'');
    }
    /**
     * @Description: 添加
     * @Author: Terry
     * @Date: 2024-01-31 21:02:21
     * @param {Request} $request
     */  
    public function create(Request $request){
        $prjCode = $request->prjCode;
        $data = $request->data;
        $data['uuid']  = createUuid();
        $data['projectCode']  = $request->prjCode;

        if(!isset($expiredTime) || empty($expiredTime)) $data['expiredTime']  = date('Y-m-d').' 23:59:59';
        $projectName = DB::table('projectInfo')->where(['code' => $request->prjCode])->value('name');
        DB::startTrans();
        try {
            $text  = $projectName.'\n(培訓簽到)'.$data['name'];
            $data['qrCode'] = $this->qrCode($data['projectCode'],$data['uuid'],$text);
            DB::table('certificate_train')->insert($data);
            DB::commit();
            $data['inDate'] = date('Y-m-d',$_SERVER['REQUEST_TIME']);
            $data['itemCount'] = 0;
            return result(SUCCESS,$data,'添加成功');
        } catch (\Exception $e) {
        // 回滚事务
            DB::rollback();
        }
        return result(FAIL,'','添加失败,请重试');
    }
    /**
     * @Description: 修改
     * @Author: Terry
     * @Date: 2024-01-31 21:02:26
     */
    public function update(Request $request){
        $data = $request->data;
        $uuid = $data['uuid'];
        $cehck = DB::table('certificate_train')->where([
            ['uuid','<>',$uuid],
            ['name','=',$data['name']],
            ['isDelete','=',0],
            ['projectCode','=',$request->prjCode],
        ])->value('id');
        if($cehck) return result(FAIL,'','名称已存在,无法修改!');

        $oldName = DB::table('certificate_train')->where([
            ['uuid','=',$uuid],
        ])->value('name');
    
        $updateData = [
            'name'=>$data['name'],
            'remark'=>$data['remark']??'',
            'corpCode'=>$data['corpCode'],
            // 'typeUuid'=>$data['typeUuid'],
            'expiredTime'=>$data['expiredTime'],
            'lecturer'=>$data['lecturer'],
        ];

        $return = [];
        if($data['name'] != $oldName)  {
            $projectName = DB::table('projectInfo')->where(['code' => $request->prjCode])->value('name');  
            $text  = $projectName.'\n(人员许可证)'.$data['name'];
            $updateData['qrCode'] = $this->qrCode($request->prjCode,$data['uuid'],$text);
            $return = ['qrCode'=>$updateData['qrCode']];
        }
        
        DB::table('certificate_train')->where('uuid',$uuid)->update($updateData);
        return result(SUCCESS,$return,'保存成功');
    }

    public function destroy(Request $request){
        $data = $request->data;
        DB::table('certificate_train')->where('uuid',$data['uuid'])->update([
            'isDelete'=>1,            
        ]);
        return result(SUCCESS,'','删除成功');
    }

        /**
     * @Description: 获取字典
     * @Author: Terry
     * @Date: 2024-01-31 22:37:41
     * @param {Request} $request
     */    
    public function getOptions(Request $request){
      $data['corp'] = DB::table('projectInfo_projectCorpInfo')
      ->where([
        ['entryTime','<>','0000-00-00 00:00:00'],
        ['projectCode','=',$request->prjCode],
      ])
      ->order('exitTime')
      ->group('corpCode')
      ->field(['corpName','corpCode'])
      ->select()->toArray();

    //   $data['type'] = DB::table('certificate_type')
    //   ->where(['isDelete'=>0 , 'projectCode' =>$request->prjCode,'type'=>'train'])
    //   ->order('id','desc')
    //   ->field(['name','uuid'])
    //   ->select()->toArray();

      return result(SUCCESS,$data,'');
  }

  public function trainLog(Request $request){
    $data = $request->data;
    $where = [
        ['tc.trainUuid','=',$data['trainUuid']]    
    ];
    
    $ext = '';
    if(!empty($data['name'])) $ext = " and wi.name like '%{$data['name']}%'";
    $list = DB::table('certificate_trainCheckIn')
    ->alias('tc')
    ->join('certification_workerInfo wi',"tc.wxappUserUuid = wi.wxappUserUuid $ext")
    ->where($where)
    ->page((int)$data['page'],(int)$data['limit'])
    ->field(['wi.name',"wi.avatarUrl",'tc.inDate'])
    ->order('tc.id desc')
    ->select();

    $count = DB::table('certificate_trainCheckIn')
    ->alias('tc')
    ->join('certification_workerInfo wi',"tc.wxappUserUuid = wi.wxappUserUuid $ext")
    ->where($where)
    ->count();

    $data = compact('list','count');
    
    return result(SUCCESS,$data,'');
  }
    /**
   * @Descripttion:二维码生成
   * @name: qrCode
   * @Author: Terry
   * @Date: 2021-04-01 22:21:14
   * @param {*} $uuid
   */
  private function qrCode($prjCode,$uuid,$text){
    $file = "image/qrcode/{$prjCode}";
    $name = time().rand(0,99999).'.jpg';
    $path = "packageC/pages/certificate/train/checkIn/checkIn?uuid={$uuid}";
    $qrCode = createQrCode($path,$name,$file);
    if(!$qrCode) return false;
    $img = new image();
    $path = $img->imgButtomAddText($qrCode,$text);

    $exp = explode('.',$path);
    $oss = new ALIOss($exp[0],$exp[1]);
    $path = $oss->upload($path);

    return $path;
  }
}
